import os
import requests
import time
import datetime
from notify import send  # 导入青龙通知模块

## 环境变量为ks_data    格式为coookie&签到sig3&运动步数sig4
# 从环境变量获取参数
##cron: 34 8,12,18,22 * * *
##new Env("快手自用")
ks_data = os.getenv("ks_data")
if not ks_data:
    print("⚠️ 请设置环境变量 ks_data")
    exit(1)
    
# 分割环境变量参数
params = ks_data.split("&")
if len(params) < 2:
    print("❌ 环境变量格式错误，应为：cookie&sign_ns_sig3&walk_ns_sig4")
    exit(1)
    
cookie_str, sign_ns_sig3 = params[:2]
walk_ns_sig4 = params[2] if len(params) >= 3 else None

# 转换Cookie字符串为字典
cookies = {}
for item in cookie_str.split(";"):
    key_value = item.split("=", 1)
    if len(key_value) == 2:
        key, value = key_value
        cookies[key.strip()] = value.strip()
        
# 公共请求头
common_headers = {
    "Host": "encourage.kuaishou.com",
    "Connection": "keep-alive",
    "User-Agent": "Mozilla/5.0 (Linux; Android 14; 23127PN0CC Build/UKQ1.230804.001; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/90.0.4430.226 KsWebView/1.8.90.728 (rel) Mobile Safari/537.36 Yoda/3.1.9-rc1 Kwai/12.8.40.38625 OS_PRO_BIT/64 MAX_PHY_MEM/15207 KDT/PHONE AZPREFIX/az2 ICFO/0 StatusHT/40 TitleHT/43 NetType/WIFI ISLP/0 ISDM/0 ISLB/0 locale/zh-cn DPS/17.148 DPP/94 SHP/2554 SWP/1200 SD/2.85625 CT/0 ISLM/0",
    "Sec-Fetch-Site": "same-origin",
    "Sec-Fetch-Mode": "cors",
    "Sec-Fetch-Dest": "empty",
    "Accept-Encoding": "gzip, deflate",
    "Accept-Language": "zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7"
}
# 存储结果
results = []
# 1. 执行签到 - 已更新为使用新奖励字段
sign_url = f"https://encourage.kuaishou.com/rest/wd/encourage/unionTask/signIn/report?__NS_sig3={sign_ns_sig3}&sigCatVer=1"
sign_headers = {
    **common_headers,
    "content-type": "application/x-www-form-urlencoded;charset=UTF-8",
    "Referer": "https://encourage.kuaishou.com/kwai/task?layoutType=4&source=MENU&hyId=encourage_earning"
}
try:
    sign_res = requests.get(sign_url, headers=sign_headers, cookies=cookies)
    sign_data = sign_res.json()
    
    if sign_data.get("result") == 1:
        # 从响应数据结构中提取奖励信息
        report_reward = sign_data.get("data", {}).get("reportRewardResult", {})
        award_info = report_reward.get("awardInpushInfo", {})
        
        # 提取标题和金币数量
        title = award_info.get("title", "签到成功")
        suffix = award_info.get("multiDayRewardSubTitleSuffix", "")
        coin_match = re.search(r'(\d+)', suffix)
        coin_count = coin_match.group(1) if coin_match else "0"
        
        # 从eventTrackingAwardInfo中获取精确的金币数量（优先级更高）
        event_award = report_reward.get("eventTrackingAwardInfo", {}).get("awardInfo", [{}])[0]
        if event_award.get("awardType") == 1:  # 1表示金币奖励
            precise_coin = str(event_award.get("amount", coin_count))
            coin_count = precise_coin if precise_coin != "0" else coin_count
        
        # 构建详情信息
        prefix = award_info.get("multiDayRewardSubTitlePrefix", "签到奖励")
        details = f"{prefix} {suffix}" if prefix else suffix
        
        # 格式化结果
        if details.strip():
            results.append(f"🎯 {title}: +{coin_count}金币 ({details})")
        else:
            results.append(f"🎯 {title}: +{coin_count}金币")
            
    else:
        error_msg = sign_data.get("error_msg", "未知错误")
        results.append(f"⚠️ 签到: {error_msg}")
        
except Exception as e:
    results.append(f"❌ 签到请求异常: {str(e)}")
    
# 添加5秒延迟
time.sleep(5)
print("⏳ 签到完成，等待5秒后执行下一步...")

# 获取当前时间
current_time = datetime.datetime.now()
current_hour = current_time.hour
is_22pm = current_hour == 22  # 22点对应晚上10点

# 新增运动步数任务（如果提供了walk_ns_sig4且当前是22点）
if walk_ns_sig4 and is_22pm:
    try:
        print("⏳ 当前是22点，开始执行运动步数任务...")
        walk_url = f"https://encourage.kuaishou.com/rest/wd/encourage/unionTask/reward?taskId=20048&rewardType=1&source=WALK_1&__NS_sig4={walk_ns_sig4}&sigCatVer=1"
        walk_headers = {
            **common_headers,
            "content-type": "application/x-www-form-urlencoded;charset=UTF-8",
            "Accept": "*/*",
            "X-Requested-With": "com.smile.gifmaker",
            "Referer": "https://encourage.kuaishou.com/activity/walk?layoutType=4&source=new_task_center&encourageTaskValidityTrack=eyJhY3Rpdml0eV9pZCI6MjAwNDgsInJlc291cmNlX2lkIjoiZWFyblBhZ2VfdGFza0xpc3RfMSIsImV4dF9wYXJhbXMiOnsiaXNTZXJ2ZXJSZWNvcmRDbGlja0FjdGlvbiI6dHJ1ZX19&encourageEventTracking=W3siZW5jb3VyYWdlX3Rhc2tfaWQiOjIwMDQ4LCJlbmNvdXJhZ2VfcmVzb3VyY2VfaWQiOiJlYXJuUGFnZV90YXNrTGlzdF8xIiwiZXZlbnRUcmFja2luZ0xvZ0luZm8iOlt7ImRlbGl2ZXJPcmRlcklkIjoiMzkyIiwibWF0ZXJpYWxLZXkiOiJUQVNLX0xJU1RfMjAwNDhfV0FMS0lOR19OT1RfUkVXQVJERUQiLCJldmVudFRyYWNraW5nVGFza0lkIjoyMDA0OCwicmVzb3VyY2VJZCI6ImVhcm5QYWdlX3Rhc2tMaXN0XzEiLCJleHRQYXJhbXMiOnsiaXNTZXJ2ZXJSZWNvcmRDbGlja0FjdGlvbiI6dHJ1ZX19XX1d"
        }
        
        walk_res = requests.get(walk_url, headers=walk_headers, cookies=cookies)
        walk_data = walk_res.json()
        
        if walk_data.get("result") == 1:
            title = walk_data.get("title", "运动步数奖励")
            desc = walk_data.get("desc", "")
            results.append(f"🚶 运动步数: {title} {desc}")
        else:
            error_msg = walk_data.get("error_msg", walk_data.get("message", "未知错误"))
            results.append(f"⚠️ 运动步数: {error_msg}")
            
    except Exception as e:
        results.append(f"❌ 运动步数请求异常: {str(e)}")
    
    # 运动步数任务后添加延迟
    time.sleep(5)
    print("⏳ 运动步数任务完成，等待5秒后查询收益...")
elif walk_ns_sig4:
    print(f"⚠️ 当前时间 {current_time.strftime('%H:%M')} 不是22点，跳过运动步数任务")
    results.append(f"⚠️ 运动步数: 当前时间 {current_time.strftime('%H:%M')} 不是22点，未执行")
else:
    print("⚠️ 未提供运动步数参数，跳过运动步数任务")

# 2. 查询收益
profit_url = "https://encourage.kuaishou.com/rest/wd/encourage/account/basicInfo"
profit_headers = {
    **common_headers,
    "Referer": "https://encourage.kuaishou.com/kwai/profit?tab=cash&layoutType=4"
}
try:
    profit_res = requests.get(profit_url, headers=profit_headers, cookies=cookies)
    profit_data = profit_res.json()
    
    if profit_data.get("result") == 1:
        data = profit_data.get("data", {})
        # 根据您提供的响应格式更新字段名
        coin_balance = data.get("coinAmountDisplay", "0")
        cash_balance = data.get("cashAmountDisplay", "0.00")
        accumulative_amount = data.get("accumulativeAmountDisplay", "0.00")
        
        # 如果以上字段不存在，尝试备用字段名
        if coin_balance == "0":
            coin_balance = data.get("coinAmount", "0")
        if cash_balance == "0.00":
            cash_balance = data.get("cashAmount", "0.00")
        if accumulative_amount == "0.00":
            accumulative_amount = data.get("accumulativeAmount", "0.00")
        
        # 添加单位转换（如有需要）
        if "." not in cash_balance:
            cash_balance = f"{float(cash_balance)/100:.2f}" if cash_balance.isdigit() else cash_balance
        
        results.append("\n💰 收益统计:")
        results.append(f"  我的金币: {coin_balance}")
        results.append(f"  我的余额: {cash_balance}元")
        results.append(f"  累计赚到: {accumulative_amount}元")
    else:
        error_msg = profit_data.get("error_msg", profit_data.get("message", "未知错误"))
        results.append(f"⚠️ 收益查询失败: {error_msg}")
        
except Exception as e:
    results.append(f"❌ 收益查询异常: {str(e)}")
    
# 打印并发送结果
result_msg = "\n".join(results)
print("="*50)
print("✨ 快手任务执行结果:")
print(result_msg)
print("="*50)
# 发送通知
send("快手任务", result_msg)